package net.telesing.tcmc.core.entity;

import java.io.*;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import net.telesing.tcmc.common.Constants;
import net.telesing.tcmc.core.impl.Util;

import net.telesing.tcmc.core.utils.FileUtil;
import org.nutz.lang.Files;
import org.nutz.mvc.upload.TempFile;

/**
 * 文件工具类（具体实现）
 *
 * Created by Zmt on 2015/11/27.
 */
public class FileEntity implements Util
{
    /**
     * 将多个文件打包，生成ZIP文件
     *
     * @param files
     * @return
     */
    public boolean packFiles(final File[] files, final String path)
    {
        boolean flag = false;
        FileInputStream fis;
        BufferedInputStream bis = null;
        FileOutputStream fos;
        ZipOutputStream zos = null;
        try
        {
            File zipFile = new File(path);
            if (zipFile.exists())
                zipFile.delete();
            if (null != files && 1 < files.length)
            {
                fos = new FileOutputStream(zipFile);
                zos = new ZipOutputStream(new BufferedOutputStream(fos));
                byte[] bufs = new byte[1024 * 10];
                for (File file : files)
                {
                    ZipEntry zipEntry = new ZipEntry(file.getName());  // 创建ZIP实体
                    zos.putNextEntry(zipEntry);
                    // 读取待压缩的文件并写进压缩包里
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis, 1024 * 10);
                    int read;
                    while (-1 != (read = bis.read(bufs, 0, 1024 * 10)))
                        zos.write(bufs, 0, read);
                }
                flag = true;
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            // 关闭流
            try
            {
                if (null != bis)
                    bis.close();
                if (null != zos)
                    zos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param tempFile
     * @param basePath
     * @return
     * @throws Exception
     */
    public String uploadFile(final TempFile tempFile, final String basePath) throws Exception
    {
        String result = null;
        File tFile = tempFile.getFile();
        String tempPath = tFile.getPath();
        String path = basePath + "temp" + Constants.SLASH;
        File tempDic = new File(path);
//        if(tempDic.exists())
//            ClearDirectory(path);
//        else
//            tempDic.mkdirs();
        if(!tempDic.exists())
            tempDic.mkdirs();
        String originalFilename = tempFile.getMeta().getFileLocalName();  // 上传时的全名
        String uuid = UUID.randomUUID().toString();
        result = moveFile(tempPath, path + uuid.substring(uuid.lastIndexOf("-") + 1) + "." + Files.getSuffixName(originalFilename), true);
        return result;
    }

    /**
     * 清空指定目录
     *
     * @param dir
     */
    public void ClearDirectory(final String dir) throws Exception
    {
        File[] files = new File(dir).listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
                ClearDirectory(dir + file.getName() + "/");  // 递归清空子目录
            file.delete();
        }
    }

    /**
     * 移动文件
     *
     * @param tempPath
     * @param newPath
     * @return
     * @throws Exception
     */
    public String moveFile(final String tempPath, final String newPath, final boolean isTemp) throws Exception
    {
        String result = null;
        File temp = new File(tempPath);
        if (temp.exists())
        {
            result = isTemp ? newPath : newPath + temp.getName();
            Files.move(temp, new File(result));
        }
        return result;
    }

    /**
     * 新建目录
     *
     * @param path
     * @return
     */
    public boolean mkdirFiles(final String path)
    {
        boolean result = false;
        File file = new File(path);
        if (!file.exists())
            result = file.mkdirs();
        return result;
    }

    /**
     * 保存数据到文件
     *
     * @param dataPath
     * @param data
     * @throws Exception
     */
    public void generateFile(final String dataPath, final String data) throws Exception
    {
        String parentPath = dataPath.substring(0, dataPath.lastIndexOf(Constants.SLASH));
        File parentDir = new File(parentPath);
        if (!parentDir.exists() || !parentDir.isDirectory())
            mkdirFiles(parentPath);
        FileOutputStream fos = null;
        PrintStream ps = null;
        try
        {
            fos = new FileOutputStream(dataPath);
            ps = new PrintStream(fos);
            ps.print(data);
        }
        finally
        {
            if (null != fos)
                fos.close();
            if (null != ps)
                ps.close();
        }
    }

    /**
     * 保存数据到文件
     *
     * @param results
     * @param dataName
     * @throws Exception
     */
    private void saveData(final byte[] results, final String dataName) throws Exception
    {
        new FileUtil().getUtil().mkdirFiles(dataName.substring(0, dataName.lastIndexOf(Constants.SLASH)));
        FileOutputStream fosData = new FileOutputStream(dataName);
        fosData.write(results);
        fosData.close();
    }

    /**
     * 从文件中读取数据
     *
     * @param dataPath
     * @return byte[]
     * @throws Exception
     */
    public byte[] readData(final String dataPath) throws Exception
    {
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        byte[] result;
        try
        {
            fis = new FileInputStream(dataPath);
            // 读二进制数据
            baos = new ByteArrayOutputStream();
            int len;
            byte[] data = new byte[1024];
            while ((len = fis.read(data)) != -1)
                baos.write(data, 0, len);
            result = baos.toByteArray();
        }
        finally
        {
            if (null != fis)
                fis.close();
            if (null != baos)
                baos.close();
        }
        return result;
    }

}
